<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="名称" prop="teroomName">
              <el-input v-model="queryParams.teroomName" placeholder="请输入名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="门店" prop="groupId">
              <el-select v-model="queryParams.groupId" filterable clearable placeholder="请选择门店" :loading="loading">
                <el-option v-for="item in options" :key="item.id" :label="item.groupName" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
                <el-option v-for="dict in room_status" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item class="float-right !mr-0 !mb-0">
              <el-button-group>
                <el-button icon="grid" :type="viewMode === 'card' ? 'primary' : 'default'" @click="viewMode = 'card'"> </el-button>
                <el-button icon="list" :type="viewMode === 'list' ? 'primary' : 'default'" @click="viewMode = 'list'"> </el-button>
              </el-button-group>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['tearoom:roomDetails:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['tearoom:roomDetails:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['tearoom:roomDetails:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple2"
              @click="handleForeverDelete()"
              v-hasPermi="['tearoom:roomDetails:foreverDelete']"
              >永久删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Refresh" :disabled="multiple2" @click="handleRecover()" v-hasPermi="['tearoom:roomDetails:recover']"
              >恢复</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['tearoom:roomDetails:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <!-- Tab 选项：真正的内容在 Lab -->
      <el-tabs v-model="activeTab" type="card" @tab-change="onTabChange">
        <el-tab-pane v-for="tab in roomStatusTabs" :key="tab.value" :label="tab.label" :name="tab.value" />
      </el-tabs>

      <template v-if="viewMode === 'card'">
        <el-row :gutter="16" v-if="roomDetailsList.length > 0">
          <el-col v-for="item in roomDetailsList" :key="item.id" :xs="24" :sm="12" :md="12" :lg="12" class="mb-4">
            <el-card class="h-full transition-colors relative overflow-hidden" :body-style="{ padding: '0' }">
              <!-- 添加渐变背景层 -->
              <div class="absolute top-0 left-0 right-0 h-[50px] pointer-events-none" :class="getStatusBackground(item.status)"></div>
              <div class="p-4 relative">
                <!-- 标题区域 -->
                <div class="flex items-center mb-3">
                  <div class="mr-2.5 flex items-center">
                    <el-image :src="defaultIconUrl" class="w-[18px] h-[18px]" />
                  </div>
                  <div class="text-[16px] font-600 flex-1">{{ item.teroomName }}</div>
                  <div class="inline-flex items-center">
                    <div class="w-1 h-1 rounded-full mr-1.5" :class="getStatusColor(item.status)"></div>
                    <el-text class="!text-xs font-bold" :type="getStatusColorType(item.status)">
                      {{ getDictLabel(room_status, item.status) }}
                    </el-text>
                  </div>
                </div>

                <!-- 信息区域 -->
                <div class="flex items-center text-[14px]">
                  <div class="flex-1">
                    <div class="mb-2.5 last:mb-0">
                      <span class="text-[#717c8e] mr-2.5">所属区域</span>
                      <span class="text-[#0070ff]">
                        {{ item.groupName }}
                      </span>
                    </div>
                    <div class="mb-2.5 last:mb-0" style="display: flex">
                      <span class="text-[#717c8e] mr-2.5">人数规格</span>
                      {{ item.teroomPepnum }}人
                    </div>
                    <div class="mb-2.5 last:mb-0" style="display: flex">
                      <span class="text-[#717c8e] mr-2.5">每小时单价</span>
                      {{ floatToFixed2(item.teroomHprice) }}元
                    </div>
                    <div class="mb-2.5 last:mb-0">
                      <span class="text-[#717c8e] mr-2.5">最少预定时间</span>
                      <span class="text-[#0b1d30] inline-block align-middle overflow-hidden text-ellipsis whitespace-nowrap max-w-[130px]">
                        {{ item.teroomNum }}
                      </span>
                    </div>
                    <div class="mb-2.5 last:mb-0">
                      <span class="text-[#717c8e] mr-2.5">营业时间</span>
                      <span class="text-[#0b1d30] inline-block align-middle overflow-hidden text-ellipsis whitespace-nowrap max-w-[130px]">
                        {{ item.startTime }}~{{ item.endTime }}
                      </span>
                    </div>
                  </div>
                  <div class="w-[100px] h-[100px]">
                    <image-preview :src="item.teroomImgurl" :width="100" :height="100" v-if="item.teroomImgurl" />
                    <el-image :src="defaultPicUrl" class="w-full h-full" v-else />
                  </div>
                </div>

                <!-- 在卡片信息区域下方添加时间轴 -->
                <div class="compact-timeline">
                  <!-- 状态标签 -->
                  <div class="status-tags flex gap-2 mb-1 ml-1 items-center justify-between">
                    <div class="flex gap-2 items-center">
                      <div class="half-hour-bars w-5 h-3 flex">
                        <div class="half-hour-bar h-full mx-px flex-1 rounded-sm transition-colors bg-red-400"></div>
                      </div>
                      <div class="text-xs text-red-500">已预定时段</div>
                      <div class="half-hour-bars w-5 h-3 flex">
                        <div class="half-hour-bar h-full mx-px flex-1 rounded-sm transition-colors"></div>
                      </div>
                      <div class="text-xs text-gray-500">可预定时段</div>
                    </div>
                    <div v-if="item.status == 2">
                      <el-text class="!text-xs font-bold" :type="getStatusColorType(item.status)"> {{ parseTime(item.recentBookStartTime, '{m}-{d} {h}:{i}') }}~{{ parseTime(item.recentBookEndTime, isSameDay(item.recentBookStartTime, item.recentBookEndTime) ? '{h}:{i}' : '{m}-{d} {h}:{i}') }} </el-text>
                    </div>
                  </div>
                  <!-- 时间轴主体 -->
                  <div class="timeline-body relative h-10">
                    <!-- 小时刻度 -->
                    <div class="hour-scales flex">
                      <div v-for="(hour, index) in visibleHourScales" :key="index" class="scale-item relative" :style="{ width: `${100 / 24}%` }">
                        <span class="absolute bottom-0 left-1/2 -translate-x-1/2 text-[10px] text-gray-400">
                          {{ hour.isNextDay && hour.display == '24' ? '次' : hour.display }}
                        </span>
                      </div>
                    </div>
                    <!-- 半小时状态条 -->
                    <div class="half-hour-bars absolute top-1/3 -translate-y-1/2 w-full h-3 flex">
                      <div
                        v-for="(segment, index) in getHalfHourSegments(item)"
                        :key="index"
                        class="half-hour-bar h-full flex-1 transition-colors"
                        :class="{
                          'bg-red-400': segment.isBooked,
                          'border-r border-gray-400 ml-1': segment.isHourMark
                        }"
                        :title="getSegmentTooltip(segment)"
                      ></div>
                    </div>
                  </div>
                </div>

                <!-- 分隔线 -->
                <el-divider class="!my-3" />

                <!-- 按钮 -->
                <div class="flex items-center px-0">
                  <el-button
                    class="flex-1 !px-2 !h-[32px] text-[13px]"
                    type="primary"
                    plain
                    @click="handleUpdate(item)"
                    icon="edit"
                    v-hasPermi="['tearoom:roomDetails:edit']"
                  >
                    编辑
                  </el-button>
                  <el-button class="flex-1 !px-2 !h-[32px] !ml-[10px] text-[13px]" type="info" plain icon="tickets" @click="handleIotDevice(item)"
                    >IoT设备</el-button
                  >
                  <div class="mx-[10px] h-[20px] w-[1px] bg-[#dcdfe6]"></div>
                  <el-button
                    v-if="item.delFlag === '0'"
                    class="!px-2 !h-[32px] text-[13px]"
                    type="warning"
                    plain
                    @click="handleDelete(item)"
                    icon="delete"
                    v-hasPermi="['tearoom:roomDetails:remove']"
                  >
                  </el-button>
                  <el-button
                    v-if="item.delFlag === '1'"
                    class="!px-2 !h-[32px] text-[13px]"
                    type="danger"
                    plain
                    @click="handleForeverDelete(item)"
                    icon="delete"
                    v-hasPermi="['tearoom:roomDetails:foreverDelete']"
                  >
                  </el-button>
                  <el-button
                    v-if="item.delFlag === '1'"
                    class="!px-2 !h-[32px] text-[13px]"
                    type="primary"
                    plain
                    @click="handleRecover(item)"
                    icon="refresh"
                    v-hasPermi="['tearoom:roomDetails:recover']"
                  >
                  </el-button>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
        <template v-else>
          <el-empty description="没有数据~" />
        </template>
      </template>

      <el-table v-loading="loading" :data="roomDetailsList" @selection-change="handleSelectionChange" v-else>
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="排序" align="center" prop="orderNum" width="60" />
        <el-table-column label="图片" align="center" prop="teroomImgurl" width="100">
          <template #default="scope">
            <image-preview :src="scope.row.teroomImgurl" :width="50" :height="50" />
          </template>
        </el-table-column>
        <el-table-column label="门店名称" align="center" prop="groupName" width="200px" />
        <el-table-column label="名称" align="center" prop="teroomName" width="120px" />
        <el-table-column label="人数规格" align="center" prop="teroomPepnum">
          <template #default="scope">
            <div>{{ scope.row.teroomPepnum }}人</div>
          </template>
        </el-table-column>
        <!-- <el-table-column label="电话" align="center" prop="teroomPhoto" /> -->
        <el-table-column label="每小时单价" align="center" prop="teroomHprice" width="120px">
          <template #default="scope">
            <div>{{ floatToFixed2(scope.row.teroomHprice) }}元</div>
          </template>
        </el-table-column>
        <el-table-column label="最少预定时间" align="center" prop="teroomNum" width="120px">
          <template #default="scope">
            <div>{{ scope.row.teroomNum }}小时</div>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="room_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="营业时间" align="center" prop="startTime" width="120px">
          <template #default="scope">
            <span>{{ scope.row.startTime }}~{{ scope.row.endTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="标签" align="center" prop="teroomTarget">
          <template #default="scope">
            <dict-tag :options="ter_target" :value="scope.row.teroomTarget ? scope.row.teroomTarget.split(',') : []" />
          </template>
        </el-table-column>
        <!-- <el-table-column label="纬度" align="center" prop="teroomLatitude" />
        <el-table-column label="经度" align="center" prop="teroomLongitude" /> -->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="140px">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['tearoom:roomDetails:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="IoT设备" placement="top">
              <el-button link type="primary" icon="List" @click="handleIotDevice(scope.row)" v-hasPermi="['tearoom:roomDetails:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top" v-if="scope.row.delFlag === '0'">
              <el-button link type="warning" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['tearoom:roomDetails:remove']"></el-button>
            </el-tooltip>
            <el-tooltip content="永久删除" placement="top" v-if="scope.row.delFlag === '1'">
              <el-button
                link
                type="danger"
                icon="Delete"
                @click="handleForeverDelete(scope.row)"
                v-hasPermi="['tearoom:roomDetails:foreverDelete']"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="恢复" placement="top" v-if="scope.row.delFlag === '1'">
              <el-button
                link
                type="primary"
                icon="Refresh"
                @click="handleRecover(scope.row)"
                v-hasPermi="['tearoom:roomDetails:recover']"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改茶室详情对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="850px" append-to-body>
      <el-form ref="roomDetailsFormRef" :model="form" :rules="rules" label-width="120px">
        <!-- 第一行：门店选择 + 图片 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="门店选择" prop="groupId">
              <el-select v-model="form.groupId" filterable clearable placeholder="请选择" :loading="loading">
                <el-option v-for="item in options" :key="item.id" :label="item.groupName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="名称" prop="teroomName">
              <el-input v-model="form.teroomName" placeholder="请输入名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第二行：轮播图 + 名称 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="图片" prop="teroomImgurl">
              <image-upload v-model="form.teroomImgurl" :limit="1" :fileSize="10" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="轮播图" prop="carouselImages">
              <image-upload v-model="form.carouselImages" :limit="6" :fileSize="10" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第三行：人数规格 + 电话 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="人数规格" prop="teroomPepnum">
              <el-input v-model="form.teroomPepnum" placeholder="请输入人数规格" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电话" prop="teroomPhoto">
              <el-input v-model="form.teroomPhoto" placeholder="请输入电话" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第四行：每小时单价 + 最少预定时间 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="每小时单价" prop="teroomHprice">
              <el-input-number v-model="form.teroomHprice" :min="0.01" :precision="2" :step="0.01" placeholder="元/小时" width="120px" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最少预定时间" prop="teroomNum">
              <el-input v-model="form.teroomNum" placeholder="请输入最少预定时间" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第五行：空间状态 + 营业时间 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="空间状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择空间状态" clearable>
                <el-option v-for="dict in room_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="营业时间" prop="startTime">
              <el-time-select v-model="form.startTime" start="00:00" step="00:30" end="23:30" placeholder="开始时间" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="排序号" prop="orderNum">
              <el-input-number v-model="form.orderNum" :min="0" :step="10" width="120px" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="endTime">
              <el-time-select v-model="form.endTime" start="00:00" step="00:30" end="23:30" placeholder="结束时间" />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第六行：经纬度 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="纬度" prop="teroomLatitude">
              <el-input v-model="form.teroomLatitude" placeholder="请输入纬度" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经度" prop="teroomLongitude">
              <el-input v-model="form.teroomLongitude" placeholder="请输入经度" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第六行：WIFI -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="WIFI名称" prop="wifiName">
              <el-input v-model="form.wifiName" placeholder="请输入WIFI名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="WIFI密码" prop="wifiPassword">
              <el-input v-model="form.wifiPassword" placeholder="请输入WIFI密码" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 独占一行的表单项：内容 + 标签 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="内容">
              <editor v-model="form.contentIntro" :min-height="192" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="标签" prop="teroomTarget">
              <el-checkbox-group v-model="form.teroomTarget">
                <el-checkbox v-for="dict in ter_target" :key="dict.value" :label="dict.value">
                  {{ dict.label }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="RoomDetails" lang="ts">
import { floatToFixed2, formatToFraction, convertToInteger } from '@/utils/index';
import {
  listRoomDetails,
  querygroupDetails,
  getRoomDetails,
  delRoomDetails,
  addRoomDetails,
  updateRoomDetails,
  recoverRoomDetails,
  foreverDeleteRoomDetails
} from '@/api/tearoom/roomDetails';
import { RoomDetailsVO, RoomGroupVO, RoomDetailsQuery, RoomDetailsForm } from '@/api/tearoom/roomDetails/types';
import defaultPicUrl from '@/assets/images/iot/device.png'; // 默认设备图片
import defaultIconUrl from '@/assets/images/iot/card-fill.svg'; // 默认设备图标
import dayjs from 'dayjs';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { ter_target } = toRefs<any>(proxy?.useDict('ter_target'));
const { room_status } = toRefs<any>(proxy?.useDict('room_status'));
const router = useRouter();
const roomDetailsList = ref<RoomDetailsVO[]>([]);
// 下拉选项数据
const options = ref<RoomGroupVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const multiple2 = ref(true);
const total = ref(0);
const viewMode = ref<'card' | 'list'>('card'); // 视图模式状态

const queryFormRef = ref<ElFormInstance>();
const roomDetailsFormRef = ref<ElFormInstance>();

const activeTab = ref('0'); // Tab 筛选
const roomStatusTabs = reactive([
  {
    label: '运营中',
    value: '0'
  },
  {
    label: '回收站',
    value: '1'
  }
]);

const ROOM_STATUS = {
  1: {
    class: 'bg-gradient-to-b from-[#cef7d7] to-transparent',
    label: '空闲',
    color: 'bg-[var(--el-color-success)]',
    type: 'success'
  },
  2: {
    class: 'bg-gradient-to-b from-[#E3F2FD] to-transparent',
    label: '使用中',
    color: 'bg-[var(--el-color-primary)]',
    type: 'primary'
  },
  3: {
    class: 'bg-gradient-to-b from-[#FFF8E1] to-transparent',
    label: '待保洁',
    color: 'bg-[var(--el-color-warning)]',
    type: 'warning'
  },
  4: {
    class: 'bg-gradient-to-b from-[#fff1f1] to-transparent',
    label: '维护中',
    color: 'bg-[var(--el-color-danger)]',
    type: 'danger'
  }
};

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const initFormData: RoomDetailsForm = {
  id: undefined,
  teroomPepnum: undefined,
  teroomName: undefined,
  teroomPhoto: undefined,
  teroomHprice: undefined,
  teroomNum: undefined,
  teroomImgurl: undefined,
  groupId: undefined,
  groupName: undefined,
  contentIntro: undefined,
  status: undefined,
  teroomTarget: [],
  teroomLatitude: undefined,
  teroomLongitude: undefined,
  startTime: undefined,
  endTime: undefined,
  delFlag: undefined,
  wifiName: undefined,
  wifiPassword: undefined
};
const data = reactive<PageData<RoomDetailsForm, RoomDetailsQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 12,
    teroomPepnum: undefined,
    teroomName: undefined,
    teroomPhoto: undefined,
    teroomHprice: undefined,
    teroomNum: undefined,
    teroomImgurl: undefined,
    groupId: undefined,
    groupName: undefined,
    contentIntro: undefined,
    status: undefined,
    teroomTarget: undefined,
    teroomLatitude: undefined,
    teroomLongitude: undefined,
    startTime: undefined,
    endTime: undefined,
    delFlag: '0'
  },
  rules: {
    groupId: [{ required: true, message: '门店不能为空', trigger: 'blur' }],
    id: [{ required: true, message: '茶室唯一id不能为空', trigger: 'blur' }],
    teroomPepnum: [{ required: true, message: '茶室人数规格不能为空', trigger: 'blur' }],
    teroomName: [{ required: true, message: '茶室名称不能为空', trigger: 'blur' }],
    teroomHprice: [{ required: true, message: '每小时单价不能为空', trigger: 'blur' }],
    orderNum: [{ required: true, message: '排序号不能为空', trigger: 'blur' }],
    teroomNum: [{ required: true, message: '最少预定时间不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
    teroomImgurl: [{ required: true, message: '茶室图片路径不能为空', trigger: 'blur' }],
    startTime: [{ required: true, message: '营业开始时间不能为空', trigger: 'blur' }],
    endTime: [{ required: true, message: '营业结束时间不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);
// 获取下拉对象
const fetchData = async () => {
  loading.value = true;
  const response = await querygroupDetails();
  options.value = response.data;
  loading.value = false;
};

/** 查询茶室详情列表 */
const getList = async () => {
  loading.value = true;
  const res = await listRoomDetails(queryParams.value);
  roomDetailsList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  roomDetailsFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: RoomDetailsVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  if (activeTab.value === '0') {
    multiple.value = !selection.length;
  }
  if (activeTab.value === '1') {
    multiple2.value = !selection.length;
  }
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加茶室详情';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: RoomDetailsVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getRoomDetails(_id);
  Object.assign(form.value, res.data);
  form.value = {
    ...res.data,
    teroomHprice: formatToFraction(res.data.teroomHprice),
    teroomTarget: res.data.teroomTarget ? res.data.teroomTarget.split(',') : []
  };
  dialog.visible = true;
  dialog.title = '修改茶室详情';
};

/** 提交按钮 */
const submitForm = () => {
  const selectedItem = options.value.find((item) => item.id === form.value.groupId);
  if (selectedItem) {
    form.value.groupName = selectedItem.groupName;
  }
  roomDetailsFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      const data = {
        ...form.value,
        teroomTarget: form.value.teroomTarget.join(','),
        teroomHprice: convertToInteger(form.value.teroomHprice)
      } as unknown as RoomDetailsVO;
      buttonLoading.value = true;
      if (data.id) {
        await updateRoomDetails(data).finally(() => (buttonLoading.value = false));
      } else {
        await addRoomDetails(data).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: RoomDetailsVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除空间编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delRoomDetails(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 永久删除按钮操作 */
const handleForeverDelete = async (row?: RoomDetailsVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否永久删除空间编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await foreverDeleteRoomDetails(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 恢复按钮操作 */
const handleRecover = async (row?: RoomDetailsVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认恢复空间编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await recoverRoomDetails(_ids);
  proxy?.$modal.msgSuccess('恢复成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'tearoom/roomDetails/export',
    {
      ...queryParams.value
    },
    `roomDetails_${new Date().getTime()}.xlsx`
  );
};

/** 跳转设备列表 */
const handleIotDevice = (row: RoomDetailsVO) => {
  const roomId = row.id;
  router.push({ path: '/equipment/iotDevice', query: { roomId: roomId } });
};

/**
 * 获得字典数据的文本展示
 *
 * @param dictType 字典类型
 * @param value 字典数据的值
 * @return 字典名称
 */
const getDictLabel = (options: Array<DictDataOption>, value: any): string => {
  const dictLabel = ref('');
  options.forEach((dict: DictDataOption) => {
    if (dict.value === value + '') {
      dictLabel.value = dict.label;
    }
  });
  return dictLabel.value;
};

// 获取状态背景色
const getStatusBackground = (status) => {
  return ROOM_STATUS[status]?.class || 'bg-gradient-to-b from-gray-100 to-transparent';
};

// 获取状态颜色
const getStatusColor = (status) => {
  return ROOM_STATUS[status]?.color || '';
};

// 获取状态颜色
const getStatusColorType = (status) => {
  return ROOM_STATUS[status]?.type || '';
};

// 生成48个半小时段数据
const getHalfHourSegments = (item) => {
  const now = dayjs();
  const segments = [];
  let currentSegmentTime = now.startOf('hour');
  // 获取该房间的timeSlot数据
  const timeSlots = item.timeSlot || [];
  // 生成当前日期+1天的时间段（48个半小时段）
  for (let i = 0; i < 48; i++) {
    const startTime = currentSegmentTime;
    // 判断当前时间是否超过30分钟
    const isCurrentMinuteOver30 = now.minute() >= 30;
    const endTime = startTime.add(30, 'minute');
    // 格式化时间为"HH:mm"作为键
    const startTimeKey = startTime.format('HH:mm');
    // 确定属于哪一天的数据（0=今天，1=明天）
    const dayIndex = startTime.isSame(now, 'day') ? 0 : 1;
    // 检查是否被预定（优先使用当天数据，若无则使用次日数据）
    let isBooked = false;
    // 核心逻辑：当前小时00分时段的特殊处理
    if (isCurrentMinuteOver30 && i === 0) {
      // 当前时间分钟超过30，且时段为当前小时的00分（如14:00-14:30）
      isBooked = true; // 强制标记为已预定
    } else {
      if (timeSlots[dayIndex] && timeSlots[dayIndex][startTimeKey] === 1) {
        isBooked = true;
      }
      if (dayIndex === 0 && timeSlots[1] && timeSlots[1][startTimeKey] === 1) {
        // 处理跨天情况
        isBooked = true;
      }
    }
    segments.push({
      startTime,
      endTime,
      startTimeKey,
      dayIndex,
      isBooked,
      isHourMark: startTime.minute() === 0, // 整点标记
      display: startTime.hour() === 0 ? '24' : startTime.format('H')
    });
    // 移动到下一个半小时段
    currentSegmentTime = endTime;
  }
  return segments;
};

// 生成可见的小时刻度（只显示整点刻度）
const visibleHourScales = computed(() => {
  const now = dayjs();
  const hours = [];
  for (let i = 0; i < 24; i++) {
    const time = now.add(i, 'hour');
    hours.push({
      time,
      display: time.hour() === 0 ? '24' : time.format('H'),
      isNextDay: !time.isSame(now, 'day')
    });
  }
  return hours;
});

// 是否是同一天
const isSameDay=(a, b)=>{
  return dayjs(a).isSame(dayjs(b), 'day')
}


// 鼠标悬停提示
const getSegmentTooltip = (segment) => {
  return `${segment.startTime.format('HH:mm')} - ${segment.endTime.format('HH:mm')}
状态: ${segment.isBooked ? '已预定' : '空闲'}`;
};

/** tab 切换 */
const onTabChange = (tabName) => {
  queryParams.value.delFlag = tabName === 'all' ? undefined : tabName;
  getList();
};

onMounted(() => {
  getList();
  fetchData();
});
</script>

<style scoped>
.compact-timeline {
  @apply mt-2 p-2 bg-gray-50 rounded-lg border border-gray-100;
}

.status-tags {
  align-items: center;
}

.timeline-body {
  min-width: 12em; /* 保证最小显示宽度 */
}

.hour-scales {
  @apply absolute top-0 left-0 w-full h-full;
}

.scale-item {
  @apply h-full border-r border-gray-200 last:border-r-0;
}

.half-hour-bar {
  background-color: #e5e7eb; /* 默认灰色 */
  &:hover {
    @apply brightness-95;
  }
}

.bg-red-400 {
  background-color: #f87171; /* 预定红色 */
}
</style>
